package com.itheima.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.Category;
import com.itheima.entity.Setmeal;
import com.itheima.entity.SetmealDish;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @PackageName: com.itheima.controller
 * @ClassName: SetmealController
 * @Description:
 * @Author: zhangcheng
 * @DateTime: 2022/6/11 8:38
 * @Version 1.0
 */

@Transactional
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        setmealService.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes().stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
        return R.success("新增套餐成功");
    }

    /**
     * 套餐分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Map<String, Object>> page(Integer page, Integer pageSize, String name) {
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        setmealService.page(pageInfo, new LambdaQueryWrapper<Setmeal>()
                .like(StringUtils.isNotEmpty(name), Setmeal::getName, name)
                .orderByDesc(Setmeal::getUpdateTime));
        List<SetmealDto> list = pageInfo.getRecords().stream().map((item) -> {
            String categoryName = categoryService.getById(item.getCategoryId()).getName();
            SetmealDto setmealDto = new SetmealDto();
            setmealDto.setCategoryName(categoryName);
            BeanUtil.copyProperties(item, setmealDto);
            return setmealDto;
        }).collect(Collectors.toList());
        Map<String, Object> data = new HashMap<>();
        data.put("records", list);
        data.put("total", (int) pageInfo.getTotal());
        return R.success(data);
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)//清除setmealCache名称下,所有的缓存数据
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        List<Setmeal> list = setmealService.list(new LambdaQueryWrapper<Setmeal>()
                .in(ids != null, Setmeal::getId, ids));
        for (Setmeal setmeal : list) {
            if (setmeal.getStatus() == 0) {
                setmealService.removeById(setmeal.getId());
                setmealDishService.remove(new LambdaQueryWrapper<SetmealDish>()
                        .eq(SetmealDish::getSetmealId, setmeal.getId()));
            } else {
                return R.error("此菜品还在售卖阶段，删除影响销售！");
            }
        }
        return R.success("删除成功");
    }

    /**
     * 批量修改套餐状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> status(@PathVariable Integer status, @RequestParam List<Long> ids) {
        List<Setmeal> list = setmealService.list(new LambdaQueryWrapper<Setmeal>()
                        .in(ids != null, Setmeal::getId, ids))
                .stream().map((setmeal) -> {
                    setmeal.setStatus(status);
                    return setmeal;
                }).collect(Collectors.toList());
        setmealService.updateBatchById(list);
        return R.success("批量修改成功");
    }

    /**
     * 根据id查询套餐信息(用于数据回显)
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id) {
        Setmeal setmeal = setmealService.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);
        setmealDto.setSetmealDishes(
                setmealDishService.list(new LambdaQueryWrapper<SetmealDish>()
                        .eq(SetmealDish::getSetmealId, setmeal.getId())));
        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto){
        setmealService.updateById(setmealDto);
        setmealDishService.remove(new LambdaQueryWrapper<SetmealDish>()
                .eq(SetmealDish::getSetmealId,setmealDto.getId()));
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes().stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
        return R.success("修改成功");
    }

    /**
     * 根据分类id查询套餐
     * @param setmeal
     * @return
     */
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + ':' + #setmeal.status")
    @GetMapping("/list")
    public R<List<Setmeal>> getSetmeal(Setmeal setmeal){
        List<Setmeal> list = setmealService.list(
                new LambdaQueryWrapper<Setmeal>()
                        .eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId())
                        .eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus())
                        .orderByDesc(Setmeal::getUpdateTime));
        return R.success(list);
    }
}
